package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.utils.DownloadUtils;
import com.itheima.health.utils.POIUtils;
import com.itheima.health.utils.WorkBookUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 套餐预约设置控制层
 */
@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {
    @Reference
    private OrderSettingService orderSettingService;

    /**
     * 上传预约设置
     * @return
     */
    @RequestMapping("/upload")
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    public Result upload(@RequestBody MultipartFile excelFile) {
        try {
            // 通过poi工具读取每一行的数据
            List<String[]> settings = POIUtils.readExcel(excelFile);
            // 套餐预约设置
            orderSettingService.setAndUpdate(settings);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }


    /**
     * 按月查询预约设置
     *
     */
    @RequestMapping("/getOrderSetting")
    public Result getOrderSetting(String date) {
        try {
            // 按月查询预约设置
            List<Map> list = orderSettingService.getOrderSetting(date+"%");
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    /**
     * 根据日期修改预约人数
     * @param orderSetting
     * @return
     */
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    @RequestMapping("/updateOrderSetting")
    public Result updateOrderSetting(@RequestBody OrderSetting orderSetting) {
        try {
            // 根据日期修改预约人数
            orderSettingService.updateOrderSetting(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }

    /**
     * 导出预约设置
     */
    @RequestMapping("/downLoadSetting")
    @PreAuthorize("hasAuthority('ORDERSETTING')")
    public void downLoadSetting (HttpServletRequest request,HttpServletResponse response) throws Exception {
//        String filename = "setting";

        response.setCharacterEncoding("UTF-8");
        List<OrderSetting> list = orderSettingService.downLoadSetting();
//        Workbook workbook = createFile(list);
        Workbook workbook = WorkBookUtils.CreateWorkBook(list);
        response.setContentType("application/octet-stream");
        // 设置返回的文件名为
        response.setHeader("Content-disposition", "attachment;filename=orderSetting.xlsx");//默认Excel名称
        response.flushBuffer();
        // 获取输出流,输出到浏览器
        workbook.write(response.getOutputStream());
        // 如果需要写出到系统,可以使用如下代码
        // workbook.write(new FileOutputStream(new File("\\file\\a.xlsx")));
        workbook.close();

    }

    private XSSFWorkbook createFile (List<OrderSetting> list) throws Exception {

            String fileName;
            // 创建工作表
            XSSFWorkbook workbook = new XSSFWorkbook();
            // 设置工作簿名
            XSSFSheet sheet = workbook.createSheet("orderSetting");
            for (int i = 0; i < list.size(); i++) {
                // 获取list中的对象
                OrderSetting orderSetting = list.get(i);
//                Object o1 = list.get(i);
                // 获取对象的字段
                Field[] fields = orderSetting.getClass().getDeclaredFields();
                int total = fields.length;
                // 创建第一行
                XSSFRow row = sheet.createRow(i);
                // 给第一行赋值
                for (int j = 0; j < total; j++) {
                    // 创建列
                    XSSFCell cell = row.createCell(j);
                    // 暴力破解
//                    fields[j].setAccessible(true);
                    // 获取对象的值o
//                    Object o = fields[j].get(orderSetting);
                    // 对应列赋值
                    // o不为空时,强转为string
                    if (orderSetting != null) {
//                        String value = o.toString();
                        Integer id = orderSetting.getId();
                        cell.setCellValue(id);
                    }
                }
            }
            // 返回工作表
        return workbook;
    }

}
